<template>
  <transition enter-active-class="slideInUp faster animated" leave-active-class="slideOutDown faster animated">
    <div class="giftModule publicVCenter" v-show="isShowAni">
      <div class="giftBox">
        <div class="nav">
          <div
            class="navItem"
            :class="{ active: giftNavIndex === index }"
            v-tap="{ methods: chooseGiftNav, giftNavIndex: index }"
            v-for="(item, index) in giftTitleList"
            :key="index"
          >
            {{ item }}
          </div>
        </div>
        <div class="giftListWrap">
          <swipe class="gift-swipe" :auto="0" v-if="giftNavIndex === 0">
            <swipe-item class="page" :key="index" v-for="(group, index) in giftList_format01">
              <div
                v-for="gift in group"
                class="item publicHvCenter"
                :key="gift.giftId"
                v-tap="{ methods: chooseGiftType, giftId: gift.giftId }"
              >
                <img class="giftImg" :src="gift.giftImg" :class="{ active: gift.giftId === currentGiftType }" />
                <div class="name">{{ gift.name }}</div>
                <div class="price publicHvCenter"><img src="@/assets/image/icon/diamond.png" class="unit" />{{ gift.price }}</div>
                <div class="activeBox publicHvCenter" v-show="gift.giftId === currentGiftType"></div>
              </div>
            </swipe-item>
          </swipe>
          <swipe class="gift-swipe" :auto="0" v-if="giftNavIndex === 1">
            <swipe-item class="page" :key="index" v-for="(group, index) in giftList_format02">
              <div
                v-for="gift in group"
                class="item publicHvCenter"
                :key="gift.giftId"
                v-tap="{ methods: chooseGiftType, giftId: gift.giftId }"
              >
                <img class="giftImg" :src="gift.giftImg" :class="{ active: gift.giftId === currentGiftType }" />
                <div class="name">{{ gift.name }}</div>
                <div class="price publicHvCenter"><img src="@/assets/image/icon/diamond.png" class="unit" />{{ gift.price }}</div>
                <div class="activeBox publicHvCenter" v-show="gift.giftId === currentGiftType"></div>
              </div>
            </swipe-item>
          </swipe>
          <swipe class="gift-swipe" :auto="0" v-if="giftNavIndex === 2">
            <swipe-item class="page" :key="index" v-for="(group, index) in giftList_format03">
              <div
                v-for="gift in group"
                class="item publicHvCenter"
                :key="gift.giftId"
                v-tap="{ methods: chooseGiftType, giftId: gift.giftId }"
              >
                <img class="giftImg" :src="gift.giftImg" :class="{ active: gift.giftId === currentGiftType }" />
                <img class="stubbleIcon" src="@/assets/image/hd2/stubble.png" />
                <div class="name">{{ gift.name }}</div>
                <div class="price publicHvCenter" v-show="enterEffect !== gift.giftId">
                  <img src="@/assets/image/icon/diamond.png" class="unit" />{{ gift.price }}
                </div>
                <div class="activeBox publicHvCenter" v-show="gift.giftId === currentGiftType"></div>
              </div>
            </swipe-item>
          </swipe>
        </div>
        <div class="txtWrap publicHCenter">
          <textarea
            v-model="content"
            :maxlength="canCustomizeInput ? 20 : 0"
            ref="text"
            cols="30"
            rows="10"
            placeholder="请输入留言内容(20字以内)"
            v-on:blur="blur"
          ></textarea>
          <div class="ylBtn publicHvCenter" v-tap="{ methods: ganerateRandomWish }">语录</div>
        </div>
        <div class="payWrap publicVCenter">
          <div class="priceWrap publicVCenter" v-show="giftNavIndex === 0 || giftNavIndex === 1">
            <img src="@/assets/image/hd2/diamondIcon.png" class="goldUnit" />
            <label class="price">{{ money }}</label>
            <div class="rechargeBtn publicHvCenter" v-tap="{ methods: toRecharge }">充值</div>
          </div>
          <div class="sendBtn publicHvCenter" v-tap="{ methods: send }" v-show="giftNavIndex === 0 || giftNavIndex === 1">赠送</div>
          <div class="sendBtn publicHvCenter purchase" v-tap="{ methods: purchaseEffect }" v-show="giftNavIndex === 2">购买</div>
        </div>
      </div>
    </div>
  </transition>
</template>
<script>
import { mapState, mapMutations } from 'vuex';
import { Swipe, SwipeItem } from 'vue-swipe';
import { sendGift, getGiftRankList, buyVipEnterEffect } from '@/api/index/index';
import { sendGiftMessage } from '@/api/chat/index';
import { POPUP_MODULE, QUICKWISH } from '@/assets/constant/index';
import { timeoutTask, generateRandom } from '@/utils/index';

const wx = require('weixin-js-sdk');

const quickWishLen = QUICKWISH.length;
export default {
  name: 'giftPopup',
  computed: {
    ...mapState({
      giftTitleList: (state) => state.live.giftTitleList,
      giftList_format01: (state) => state.live.giftList_format01,
      giftList01: (state) => state.live.giftList01,
      giftList_format02: (state) => state.live.giftList_format02,
      giftList02: (state) => state.live.giftList02,
      giftList_format03: (state) => state.live.giftList_format03,
      giftList03: (state) => state.live.giftList03,
      currentGiftType: (state) => state.app.currentGiftType,
      money: (state) => state.user.money,
      freeSendGift: (state) => state.user.freeSendGift,
      giftNavIndex: (state) => state.live.giftNavIndex,
      enterEffect: (state) => state.user.enterEffect,
      canCustomizeInput: (state) => state.app.canCustomizeInput,
    }),
  },
  watch: {
    canCustomizeInput(value) {
      if (!value) {
        this.content = '';
      }
    },
    giftNavIndex(newVal) {
      if (newVal === 0) {
        this.setCurrentGiftType(this.giftList_format01[0][0].giftId);
        this.priceDisplay = this.getCurrentPriceByGiftId(this.currentGiftType);
      } else if (newVal === 1) {
        this.setCurrentGiftType(this.giftList_format02[0][0].giftId);
        this.priceDisplay = this.getCurrentPriceByGiftId(this.currentGiftType);
      } else if (newVal === 2) {
        this.setCurrentGiftType(this.giftList_format03[0][0].giftId);
        this.priceDisplay = this.getCurrentPriceByGiftId(this.currentGiftType);
      }
    },
  },
  created() {
    getGiftRankList()
      .then((res) => {
        console.log('giftRankList', res);
        if (res.list.length > 0) {
          const tmpList = res.list.length > 5 ? res.list.slice(0, 5) : res.list;
          this.happyValList = tmpList.map((item) => {
            return {
              ...item,
              type: item.type === '1' ? '男方' : '女方',
            };
          });
        } else {
          for (let i = 0; i < 5; i += 1) {
            this.happyValList.push({
              avator: require('../../assets/image/defaultHeadImg.png'),
              size: 0,
              type: '',
            });
          }
        }
      })
      .catch((err) => {
        console.log(err);
      });
  },
  components: {
    Swipe,
    SwipeItem,
  },
  data() {
    return {
      isShowAni: false,
      content: '',
      priceDisplay: 0,
      happyValList: [],
    };
  },
  mounted() {
    // 执行弹出动画
    this.showAniStart();
    this.priceDisplay = this.getCurrentPriceByGiftId(this.currentGiftType);
  },
  methods: {
    ...mapMutations({
      setCurrentGiftType: 'app/setCurrentGiftType',
      setUserInfo: 'user/setUserInfo',
      togglePopup: 'app/togglePopup',
      setOrigin: 'app/setOrigin',
      setGiftNavIndex: 'live/setGiftNavIndex',
    }),
    blur() {
      window.scrollTo(0, -document.documentElement.clientHeight);
    },
    ganerateRandomWish() {
      this.content = QUICKWISH[generateRandom(0, quickWishLen)];
    },
    showAniStart() {
      this.isShowAni = true;
    },
    hideAniStart() {
      this.isShowAni = false;
    },
    chooseGiftType(g) {
      this.setCurrentGiftType(g.giftId);
      this.priceDisplay = this.getCurrentPriceByGiftId(g.giftId);
    },
    chooseGiftNav(g) {
      console.log(g);
      this.setGiftNavIndex(g.giftNavIndex);
    },
    validateSend() {
      let flag = true;
      const giftPrice = this.getCurrentPriceByGiftId(this.currentGiftType);
      console.log(giftPrice);
      if (this.freeSendGift) {
        flag = true;
      } else if (giftPrice > this.money) {
        this.$toast.center('余额不足,请充值!');
        flag = false;
        this.setOrigin('sendGift');
        this.togglePopup();
        timeoutTask(() => {
          this.togglePopup(POPUP_MODULE.rechargeModule.key);
        }, 200);
      }
      return flag;
    },
    sendBroadcast() {
      sendGiftMessage(this.content);
    },
    send() {
      if (!this.validateSend()) {
        return;
      }

      this.$loading('发送中...');
      sendGift()
        .then((res1) => {
          this.$loading.close();
          // 更新 用户余额
          this.setUserInfo({
            money: res1.result.balance,
          });
          this.$toast.center('发送成功!');
          this.togglePopup();
          return this.sendBroadcast(); // 发送礼物的广播
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getCurrentPriceByGiftId(giftId) {
      let price;
      if (this.giftNavIndex === 0) {
        const choosedGift = this.giftList01.find((item) => item.giftconst === giftId);
        price = choosedGift.giftprice;
      } else if (this.giftNavIndex === 1) {
        const choosedGift = this.giftList02.find((item) => item.giftconst === giftId);
        price = choosedGift.giftprice;
      } else if (this.giftNavIndex === 2) {
        const choosedGift = this.giftList03.find((item) => item.giftconst === giftId);
        price = choosedGift.giftprice;
      }
      return price;
    },
    toRecharge() {
      console.log('***跳转地址***');
      this.setOrigin('sendGift');
      console.log(
        `/pages/pay/pay?openId=${this.$store.state.user.openId}&userId=${this.$store.state.user.userId}&total=${this.priceDisplay}&giftId=${this.currentGiftType}&origin=${this.$store.state.app.origin}`,
      );
      wx.miniProgram.navigateTo({
        url: `/pages/pay/pay?openId=${this.$store.state.user.openId}&userId=${this.$store.state.user.userId}&total=${this.priceDisplay}&giftId=${this.currentGiftType}&origin=${this.$store.state.app.origin}`,
      });
    },
    purchaseEffect() {
      console.log(this.currentGiftType, this.priceDisplay);
      if (this.enterEffect === this.currentGiftType) {
        this.$toast.center('已拥有当前进场特效!');
        return;
      }
      buyVipEnterEffect(this.currentGiftType)
        .then((res) => {
          console.log(res);
          if (res.code === '200') {
            this.$toast.center('进场特效购买成功!');
          } else if (res.code === '100') {
            // 喵钻不足 跳转支付
            console.log('***跳转地址***');
            localStorage.setItem('tmpGiftId', this.currentGiftType);
            this.setOrigin('purchaseEnterEffect');
            console.log(
              `/pages/pay/pay?openId=${this.$store.state.user.openId}&userId=${this.$store.state.user.userId}&total=${this.priceDisplay}&origin=${this.$store.state.app.origin}`,
            );
            wx.miniProgram.navigateTo({
              url: `/pages/pay/pay?openId=${this.$store.state.user.openId}&userId=${this.$store.state.user.userId}&total=${this.priceDisplay}&origin=${this.$store.state.app.origin}`,
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
};
</script>
<style lang="less" scoped>
@import 'vue-swipe/dist/vue-swipe.css';

.giftModule {
  position: absolute;
  width: 100%;
  bottom: 0;
  flex-direction: column;
  .giftBox {
    width: 750px;
    height: 906px;
    border-top-right-radius: 24px;
    border-top-left-radius: 24px;
    background-color: rgba(23, 23, 44, 0.96);
    .nav {
      height: 80px;
      display: flex;
      align-items: flex-end;
      padding: 0 32px;
      margin-bottom: 2.5vw;
      position: relative;
      .navItem {
        font-size: 26px;
        font-weight: 400;
        margin-left: 50px;
        color: rgba(255, 255, 255, 0.3);
        padding-bottom: 4px;
        &.active {
          font-size: 28px;
          font-weight: 500;
          color: #ffffff;
          border-bottom: 4px solid #fff;
        }
      }
    }
    .giftListWrap {
      width: 100%;
      height: 480px;
      .gift-swipe {
        .page {
          width: 100%;
          height: 100%;
          position: absolute;
          padding: 0 2%;
          .item {
            position: relative;
            flex-direction: column;
            margin: 24px 0;
            width: 25%;
            float: left;
            .giftImg {
              width: 85px;
              height: 85px;
              &.active {
                animation-name: bounceIn;
                animation-duration: 2.5s;
                animation-iteration-count: infinite;
                animation-delay: 0;
              }
            }
            .stubbleIcon {
              width: 84px;
              height: 40px;
              position: absolute;
              top: -10px;
              right: -30px;
            }
            .name {
              font-size: 24px;
              color: #fff;
              margin-top: 20px;
            }
            .price {
              margin-top: 6px;
              color: rgba(255, 255, 255, 0.6);
              font-size: 20px;
              .unit {
                width: 28px;
                height: 21px;
                margin-right: 6px;
              }
            }
            .activeBox {
              position: absolute;
              top: -15px;
              width: 110px;
              height: 110px;
              border: 3px solid #ddd;
              border-image: linear-gradient(#e12b95, #cb63ee) 1 1;
            }
          }
        }
      }
      .mint-swipe::v-deep {
        .mint-swipe-items-wrap {
          position: relative;
          height: 100%;
        }
        .mint-swipe-indicators {
          display: flex;
          justify-content: center;
          position: absolute;
          bottom: 0;
          width: 100%;
          .mint-swipe-indicator {
            width: 6px;
            height: 6px;
            background-color: #ffffff;
            border-radius: 3px;
            margin: 0 4px;
            &.is-active {
              width: 10px;
            }
          }
        }
      }
    }
    .txtWrap {
      margin-top: 48px;
      position: relative;
      textarea {
        width: 686px;
        height: 116px;
        font-size: 28px;
        padding: 20px 32px;
        padding-right: 100px;
        color: #fff;
        outline: none;
        box-sizing: border-box;
        background-color: transparent;
        border: 2px solid;
        border-image: linear-gradient(99deg, #45f6fe 0%, #c026ed 100%) 1 1;
        &::placeholder {
          font-size: 28px;
          color: #756ea1;
        }
      }
      .ylBtn {
        width: 88px;
        height: 48px;
        background: #231f44;
        border-radius: 10px;
        font-size: 28px;
        font-weight: 400;
        color: #c2baf5;
        position: absolute;
        top: 32px;
        right: 48px;
      }
    }
    .payWrap {
      justify-content: space-between;
      padding-left: 20px;
      padding-right: 38px;
      margin-top: 49px;
      position: relative;
      .priceWrap {
        .goldUnit {
          width: 32px;
          height: 26px;
          margin-top: 8px;
        }
        .price {
          font-size: 28px;
          font-weight: 400;
          color: #ffffff;
          margin-left: 10px;
        }
        .rechargeBtn {
          width: 112px;
          height: 52px;
          background-image: url('../../assets/image/hdBar/rechargeBtn.png');
          background-size: 100% 100%;
          font-size: 32px;
          font-weight: 400;
          color: #cd655a;
          margin-left: 25px;
        }
      }
      .sendBtn {
        width: 128px;
        height: 52px;
        background: linear-gradient(300deg, #c76bfb 0%, #ea1775 100%);
        background-image: url('../../assets/image/hdBar/sendBtn.png');
        background-size: 100% 100%;
        font-size: 32px;
        color: #ffffff;
        &.purchase {
          position: absolute;
          right: 38px;
          top: 0px;
        }
      }
    }
  }
}
</style>
